<template>
  <div class="container">
    <el-row type="flex" justify="space-between">
      <div class="main">
        <!-- 写游记 -->
        <h2>发表新攻略</h2>
        <p>分享你的个人游记，让更多人看到哦！</p>
        <el-form>
          <el-form-item>
            <el-input placeholder="请输入标题" v-model="form.title" />
          </el-form-item>
          <!-- 富文本部分 -->
          <div class="fu">
            <client-only>
              <vue-editor
                v-model="form.content"
                :editorToolbar="customToolbar"
                @image-added="handleImageAdded"
                style="height:458px;margin-bottom:50px"
              />
            </client-only>
          </div>

          <el-form-item label="选择城市" class="xuan">
            <el-autocomplete
              class="el-autocomplete"
              v-model="form.city"
              :fetch-suggestions="getCityList"
              placeholder="请搜索游玩城市"
              :trigger-on-focus="false"
              :highlight-first-item="true"
              @select="handleSelect"
            ></el-autocomplete>
          </el-form-item>
        </el-form>
        <div class="creat-button">
          <el-button type="primary" style="padding:9px 15px;font-size:12px" @click="publishPost">发布</el-button>
          <span>
            或者
            <a href="javascript:;" @click="saveDraft">保存到草稿</a>
          </span>
        </div>
      </div>
      <div class="aside">
        <!-- 草稿箱 -->
        <div class="draft-box">
          <h4 class="draft-title">草稿箱（{{this.$store.state.history.postList.length||0}}）</h4>
          <div class="draft-list">
            <!-- //草稿列表 -->
            <div class="draft-item" v-for="(item,index) in draftList" :key="index">
              <div @click="getDraft(index)" class="draft-post-title">
                {{ item.title }}
                <span class="iconfont el-icon-edit" />
              </div>
              <p>{{ $moment(item.time).format('YYYY-MM-DD hh:mm') }}</p>
            </div>
          </div>
        </div>
      </div>
    </el-row>
    <!-- 临时登录 -->
    <div class="simplelogin">
      <SimpleLogin :showDialog="centerDialogVisible"></SimpleLogin>
    </div>
  </div>
</template>

<script>
import SimpleLogin from "@/components/user/SimpleLogin.vue";
export default {
  components: {
    SimpleLogin
  },
  data() {
    return {
      form: {
        title: "",
        content: "",
        city: ""
      },
      centerDialogVisible: false,
      customToolbar: [
        ["bold", "italic", "underline", "strike"],
        [{ header: 1 }, { header: 2 }],
        ["image"]
      ]
    };
  },
  computed: {
    //草稿列表
    draftList() {
      // 判断当前是否处在登录状态
      const token = this.$store.state.user.userInfo.token;
      if (token) {
        return this.$store.state.history.postList;
      }
    }
  },
  methods: {
    //富文本框的图片上传
    handleImageAdded(file, Editor, cursorLocation, resetUploader) {
      var formdata = new FormData();
      formdata.append("files", file);
      //			发送ajax上传图片
      this.$axios({
        url: "/upload",
        method: "post",
        data: formdata
      })
        .then(res => {
          console.log("这里是上传图片到编辑器", res);
          const { data } = res.data;
          // 这里需要拼接基准路径,然后才能将图片显示出来
          let url = this.$axios.defaults.baseURL + data.url;
          //下面是固定写法，将图片插入到编辑器中
          Editor.insertEmbed(cursorLocation, "image", url);
          //有一个必须要做的事情就是重置上传组件
          resetUploader();
        })
        .catch(err => {
          //这里是捕获错误
          console.log(err);
        });
    },
    //搜索城市
    searchCityName(cityname) {
      return this.$axios({
        url: "/airs/city",
        params: {
          name: cityname || "南京"
        }
      }).then(res => {
        const { data } = res.data;
        console.log("城市名称", res);
        //将城市名称返回出去
        const citylist = data.map(element => {
          return { ...element, value: element.name };
        });
        return citylist;
      });
    },
    //获取显示城市列表
    async getCityList(selectValue, showList) {
      //返回输入建议的方法，
      //城市获得焦点的时候触发，selectValue是选中的值，cb(showList)是回调函数，获取要展示的城市列表
      const citylist = await this.searchCityName(selectValue);
      if (citylist.length > 0) {
        showList(citylist);
      } else {
        var suggestion = [
          {
            value: "抱歉，不支持该城市"
          }
        ];
        //显示提示信息
        showList(suggestion);
      }
    },
    //点击选中建议项时触发
    handleSelect(item) {
      // console.log(item);
      this.form.city = item.name;
    },
    // 发布文章
    publishPost() {
      //获取token
      const token = this.$store.state.user.userInfo.token;
      // token不能为空
      if (!token) {
        this.$message({
          message: "请先登录",
          type: "error"
        });
        // 弹出登录窗
        this.centerDialogVisible = true;
      }
      //标题和城市&内容不能为空
      if (
        this.form.city == "" ||
        this.form.content == "" ||
        this.form.title == ""
      ) {
        return this.$message({
          type: "warning",
          message: "请填写完整"
        });
      }
      this.$axios({
        url: "/posts",
        method: "POST",
        headers: {
          Authorization: "Bearer " + token
        },
        data: this.form
      }).then(res => {
        console.log("发布成功", res);
        const { data } = res;
        this.$message({
          message: "发布成功",
          type: "success"
        });
        //清空输入框的数据
        this.form = {
          title: "",
          content: "",
          city: ""
        };
      });
    },
    //保存草稿
    saveDraft() {
      //定义一个对象，存储草稿数据
      let posts = {
        ...this.form,
        time: Date.now()
      };
      //将该数据存储到store仓库中
      this.$store.commit("history/addPostList", { ...posts });
    },
    //获取草稿
    getDraft(index) {
      //将当前的数据存到form中
      // this.form = { ...this.$store.state.history.postList[index] };
      //记住剩余参数是放到后面的
      const { time, ...props } = this.$store.state.history.postList[index];
      console.log("剩余参数", props);
      this.form = props;
    }
  }
};
</script>

<style lang="less" scoped>
.container {
  width: 1000px;
  margin: 0 auto;
  padding-bottom: 20px;
  .main {
    width: 750px;
    h2 {
      font-weight: 400;
      font-size: 22px;
      margin-bottom: 10px;
    }
    p {
      font-size: 12px;
      color: #999;
      margin-bottom: 10px;
    }
    .creat-button {
      span {
        margin-left: 10px;
        font-size: 14px;
        a {
          color: orange;
        }
      }
    }
    .fu {
      margin-bottom: 70px;
    }
  }
  .aside {
    width: 200px;
    height: 600px;
    .draft-box {
      border: 1px solid #ddd;
      padding: 10px;
    }
    .draft-title {
      margin-bottom: 10px;
      font-weight: 400;
      color: #666;
    }
    .draft-list {
      overflow-y: scroll;
      .draft-item {
        font-size: 14px;
        margin-bottom: 5px;
        .draft-post-title {
          cursor: pointer;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          &:hover {
            color: orange;
            text-decoration: underline;
          }
          span {
            margin-left: 5px;
          }
        }
        p {
          color: #999;
        }
      }
    }
  }
}
</style>
